package com.graduation.lastproject.controller.hotellist;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.graduation.lastproject.entity.HotelInfo;
import com.graduation.lastproject.entity.User;
import com.graduation.lastproject.service.hotellist.HotellistService;
import com.graduation.lastproject.util.shiro.LoginsToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.graduation.lastproject.util.stringUtil.trimFirstAndLastChar;


import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.security.util.Resources_es;

@Controller
@RequestMapping("/hotellist")
public class HotellistController {
    private static Logger logger=LoggerFactory.getLogger(HotellistController.class);
    @Autowired
    HotellistService hotellistService;

    @RequestMapping(value = "{page}")
    public Object topages(@PathVariable String page,HttpServletRequest request){
        if(page.equals("hotelPay")){
            request.setAttribute("inTime",request.getParameter("inTime"));
            request.setAttribute("outTime",request.getParameter("outTime"));
            request.setAttribute("hotelNameRoom",request.getParameter("hotelNameRoom"));
            request.setAttribute("hotelId",request.getParameter("hotelId"));
            request.setAttribute("trade_out",request.getParameter("trade_out"));
            request.setAttribute("hotelRoom",request.getParameter("hotelRoom"));
            request.setAttribute("hotelPri",request.getParameter("hotelPri"));

            /*4.1 获取当前登录用户的vip积分 和 积分*/
            int uservipScore=request.getSession().getAttribute("userInfo") != null ? ((User)request.getSession().getAttribute("userInfo")).getVip() : 0;
            int userIntegral=request.getSession().getAttribute("userInfo") != null ?((User)request.getSession().getAttribute("userInfo")).getIntegral() : 0;
            request.setAttribute("uservipScore",uservipScore);
            request.setAttribute("userIntegral",userIntegral);
        }
        String pagenew="listpage/"+page;
        return pagenew;
    }


    /*酒店列表*/
    @RequestMapping(value = "/listpage"/*,method = RequestMethod.POST*/)
    public Object listpage(HttpServletRequest request,
                           @RequestParam(value = "pageNum" ,defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize,
                           Model model){
        Map<String,Object> map = parameters(request);
        PageHelper.startPage(pageNum,pageSize);
        List<HotelInfo> list=hotellistService.getAllInfo(map);
        //将查询到的数据放入pagehepler中
        PageInfo<HotelInfo> pageInfo = new PageInfo<HotelInfo>(list);
        // 将查询到的数据存到返回
        model.addAttribute("pageInfo", pageInfo);
        return "listpage/hotellist";
        }

    /*酒店详情*/
    @RequestMapping(value = "/listDetails",params="id")
    public Object listDetails(HttpServletRequest request, @RequestParam("id")String id){
         /*    String hotelId=request.getParameter("id");*/
        String hotelId=id;  //酒店id 唯一标识
        /*获取酒店相关信息*/
        HotelInfo hotelInfo =hotellistService.getAllInfoById(hotelId);
        /*获取酒店相关评论 日期降序*/
        List<Map<String,Object>> list=hotellistService.getAllReviewInfo(hotelId);
        logger.info("酒店的所有信息:"+hotelInfo);
        String server = hotelInfo.getServiceFacilities();       //数据  [1,2,4,5]
        String[] replaceAll = server.substring(1,server.length()-1).split(",");
        StringBuffer stringBuffer=new StringBuffer();
        /*for (String s : replaceAll) {*/
        for (int i = 0; i <replaceAll.length; i++) {
            if(replaceAll[i].equals("1")){
                stringBuffer.append("暖气");
            }else if(replaceAll[i].equals("2")){
                stringBuffer.append("停车场");
            }else if(replaceAll[i].equals("3")){
                stringBuffer.append("投影设备");
            }else if(replaceAll[i].equals("4")){
                stringBuffer.append("洗衣机");
            }else {
                stringBuffer.append("浴缸");
            }
            if(i!=replaceAll.length-1){
                stringBuffer.append("---");
            }
        }
        logger.info("服务设施:"+stringBuffer);
        request.setAttribute("servers",stringBuffer);
        request.setAttribute("hotelInfo",hotelInfo);
        request.setAttribute("reviewlist",list);
        return "listpage/listDetails";
    }

    @RequestMapping(value = "BookhotelInfo",method = RequestMethod.POST)
    @ResponseBody
    public Object BookhotelInfo(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>();
        Map<String,Object> map = parameters(request);
       /* //修改hotel_info表数据
        String hotelId=map.get("hotelId").toString();
        String hotelRoomType=map.get("hotelRoom").toString();
        hotellistService.updataHotelNumInfo(hotelId,hotelRoomType);*/
        String out_trade_no=trimFirstAndLastChar.onlyout_trade_no();
        map.put("out_trade_no",out_trade_no);
        //往bookorder表插入数据
        int i=hotellistService.insertBookHotelInfo(map);
        result.put("msg",i==1 ? out_trade_no:"操作失败");
        return result;
    }

    /*用户未提交订单 删除BookhotelInfo方法添加的数据*/
    @RequestMapping(value = "/deleteOrderInfo" ,method = RequestMethod.POST)
    public void deleteOrderInfo(HttpServletRequest request){
       /* Map<String,Object> result=new HashMap<>();*/
        String trade_out=request.getParameter("trade_out");
        hotellistService.deleteOrderInfo(trade_out);
    }


    //用户登录
    @RequestMapping(value = "/logined",method = RequestMethod.POST)
    @ResponseBody
    public Object login(User user, Model model){
        String User="User";
        Map<String,Object> result=new HashMap<>();
        //1 获取Subject
        Subject subject= SecurityUtils.getSubject();
        /*if(!subject.isAuthenticated()){   */
        //创建令牌，封装用户数据
        LoginsToken token=new  LoginsToken(user.getRealname(),user.getPassword(),User);;
        try {
            subject.login(token);
            result.put("msg","登录成功");
            return result;
        }catch (UnknownAccountException e){
            result.put("msg","登录名未注册,登录失败");
            return result;
        }catch (IncorrectCredentialsException e){
            result.put("msg","密码错误,登录失败");
            return result;
        }
        /*}*/

    }
    /*request装map*/
    public final Map<String,Object> parameters(HttpServletRequest request){
        Map<String,Object> param=new HashMap<>();
        if(request!=null){
            Enumeration<String> keys=request.getParameterNames();
            while (keys.hasMoreElements()) {
                 String key=keys.nextElement();
                try {
                    String value=request.getParameter(key);
                    param.put(key,value);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return param;
    }
}

